<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="成交日期" style="width: 308px">
        <el-date-picker
            v-model="daterangeTradeDate"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="证券代码" prop="stockCode">
        <el-input
            v-model="queryParams.stockCode"
            placeholder="请输入证券代码"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="证券名称" prop="stockName">
        <el-input
            v-model="queryParams.stockName"
            placeholder="请输入证券名称"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="操作" prop="operation">
        <el-input
            v-model="queryParams.operation"
            placeholder="请输入操作"
            clearable style="width: 240px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="证券账号" prop="accountNos">
        <el-select
            v-model="queryParams.accountNos"
            placeholder="请选择证券账号"
            clearable
            multiple
            style="width: 240px"
        >
          <el-option
              v-for="item in accountOptions"
              :key="item.accountNo"
              :label="item.accountName"
              :value="item.accountNo"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-input
            v-model="queryParams.createTime"
            placeholder="请输入创建时间"
            clearable style="width: 240px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['stock:settlement:edit']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['stock:settlement:remove']"
        >删除
        </el-button>
        <el-button
            type="warning"
            plain
            icon="Refresh"
            @click="handleFullSync"
        >生成清仓和持仓统计
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading"
              :data="settlementList"
              @selection-change="handleSelectionChange"
              show-summary
              :summary-method="getSummaries">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="成交日期" align="center" prop="tradeDate">
        <template #default="scope">
          <span>{{ parseTime(scope.row.tradeDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属账号" align="center" prop="accountNo">
        <template #default="scope">
          {{ getAccountName(scope.row.accountNo) }}
        </template>
      </el-table-column>
      <el-table-column label="证券代码" align="center" prop="stockCode"/>
      <el-table-column label="证券名称" align="center" prop="stockName" width="150px"/>
      <el-table-column label="操作" align="center" prop="operation"/>
      <el-table-column label="成交数量" align="center" prop="tradeQuantity"/>
      <el-table-column label="成交均价" align="center" prop="averagePrice"/>
      <el-table-column label="成交金额" align="center" prop="tradeAmount"/>
      <el-table-column label="费用合计" align="center" prop="totalFees"/>
      <el-table-column label="发生金额" align="center" prop="occurredAmount"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="170px">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="成交时间" align="center" prop="tradeTime" v-if="columns.tradeNo.visible"/>
      <el-table-column label="成交编号" align="center" prop="tradeNo" v-if="columns.tradeNo.visible"/>
      <el-table-column label="合同编号" align="center" prop="contractNo" v-if="columns.contractNo.visible"/>
      <el-table-column label="手续费" align="center" prop="commission" v-if="columns.commission.visible"/>
      <el-table-column label="印花税" align="center" prop="stampDuty" v-if="columns.stampDuty.visible"/>
      <el-table-column label="其他杂费" align="center" prop="otherFees" v-if="columns.otherFees.visible"/>
      <el-table-column label="证管费" align="center" prop="regulatoryFee" v-if="columns.regulatoryFee.visible"/>
      <el-table-column label="经手费" align="center" prop="handlingFee" v-if="columns.handlingFee.visible"/>
      <el-table-column label="其他费用" align="center" prop="otherCharges" v-if="columns.otherCharges.visible"/>
      <el-table-column label="交易市场" align="center" prop="exchange" v-if="columns.exchange.visible"/>
      <el-table-column label="余额" align="center" prop="balance" v-if="columns.balance.visible"/>
      <el-table-column label="本次金额" align="center" prop="currentAmount" v-if="columns.currentAmount.visible"/>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100, 200,500]"
        @pagination="getList"
    />

    <!-- 用户导入对话框 -->
    <el-dialog
        :title="upload.title"
        v-model="upload.open"
        width="400px"
        append-to-body
        @close="handleUploadClose"
    >
      <div style="margin-bottom: 20px;"></div>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Settlement">
import {getToken} from "@/utils/auth";
import {delSettlement, generateStat, listSettlement} from "@/api/stock/settlement";
import {listAccount} from "@/api/stock/account";
import {isValidDateFormat} from "@/utils/validate.js";
import {formatCurrency} from "@/utils/format.js";

const {proxy} = getCurrentInstance();

const settlementList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const daterangeTradeDate = ref([]);
const accountOptions = ref([]);
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + getToken()},
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/stock/settlement/importData",
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    operation: null,
    tradeDate: null,
    stockCode: null,
    stockName: null,
    createTime: null,
    accountNos: [],
  },
  rules: {}
});

const {queryParams} = toRefs(data);

const columns = ref({
  tradeTime: {label: "成交时间", visible: false},
  contractNo: {label: "合同编号", visible: false},
  tradeNo: {label: "成交编号", visible: false},
  commission: {label: "手续费", visible: false},
  stampDuty: {label: "印花税", visible: false},
  otherFees: {label: "其他杂费", visible: false},
  regulatoryFee: {label: "证管费", visible: false},
  handlingFee: {label: "经手费", visible: false},
  otherCharges: {label: "其他费用", visible: false},
  currentAmount: {label: "本次金额", visible: false},
  balance: {label: "余额", visible: false},
  exchange: {label: "交易市场", visible: false}
});

/** 查询交易交割记录列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeTradeDate && '' !== daterangeTradeDate) {
    queryParams.value.beginTradeDate = daterangeTradeDate.value[0];
    queryParams.value.endTradeDate = daterangeTradeDate.value[1];
  }
  // 将数组转为字符串
  let accountNosString = '';
  if (Array.isArray(queryParams.value.accountNos) && queryParams.value.accountNos.length > 0) {
    accountNosString = queryParams.value.accountNos.join(',');
  } else if (typeof queryParams.value.accountNos === 'string' && queryParams.value.accountNos) {
    accountNosString = queryParams.value.accountNos;
  }
  const queryParamCopy = {...queryParams.value, accountNos: accountNosString};
  listSettlement(queryParamCopy).then(response => {
    settlementList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

const getSummaries = (param) => {
  const {columns, data} = param
  const sums = []

  columns.forEach((column, index) => {
    if (index === 1) {
      sums[index] = '统计'
    }
    if (column.property === 'occurredAmount') {
      const values = data.map(item => Number(item[column.property]))
      const sum = values.reduce((prev, curr) => prev + curr, 0)
      sums[index] = formatCurrency(sum);
    }
    if (column.property === 'totalFees') {
      const values = data.map(item => Number(item[column.property]))
      const sum = values.reduce((prev, curr) => prev + curr, 0)
      sums[index] = formatCurrency(sum);
    }
    if (column.property === 'tradeQuantity') {
      const values = data.map(item => Number(item[column.property]))
      const sum = values.reduce((prev, curr) => prev + curr, 0)
      sums[index] = formatCurrency(sum);
    }

  })

  return sums
}

/** 搜索按钮操作 */
function handleQuery() {
  // 直接校验创建时间格式
  if (queryParams.value.createTime && !isValidDateFormat(queryParams.value.createTime)) {
    proxy.$modal.msgError("创建时间格式不正确，请输入如：2025-01-01 12:10:22");
    return;
  }

  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeTradeDate.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除交易交割记录？').then(function () {
    return delSettlement(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}


/** 导入按钮操作 */
function handleImport() {
  upload.title = "交割单导入";
  upload.open = true;
  upload.selectedFile = null;
}

/** 获取账户列表 */
function getAccountList() {
  listAccount({}).then(response => {
    accountOptions.value = response.rows;
  });
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件选择处理 */
const handleFileChange = (file, fileList) => {
  upload.selectedFile = file;
};
/** 文件删除处理 */
const handleFileRemove = (file, fileList) => {
  upload.selectedFile = null;
};

/** 上传对话框关闭时重置表单 */
function handleUploadClose() {
  upload.selectedFile = null;
  proxy.$refs["uploadRef"].clearFiles();
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  proxy.$modal.closeLoading();
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$modal.alert(response.msg);
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  const file = upload.selectedFile;
  if (
      !file ||
      file.length === 0 ||
      (!file.name.toLowerCase().endsWith(".xls") &&
          !file.name.toLowerCase().endsWith(".xlsx"))
  ) {
    proxy.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。");
    return;
  }
  // 显示加载提示
  proxy.$modal.loading("正在导入数据，请稍候...");
  // 设置上传状态
  upload.isUploading = true;
  // 提交文件
  proxy.$refs["uploadRef"].submit();

}

/** 获取账户名称 */
function getAccountName(accountNo) {
  if (!accountNo) return '';
  const account = accountOptions.value.find(item => item.accountNo === accountNo);
  return account ? account.accountName : accountNo;
}

/** 生成统计数据 */
function handleFullSync() {
  proxy.$modal.confirm('是否确认执行生成统计数据?').then(function () {
    generateStat({startDate: ''});
    proxy.$modal.msgSuccess("已提交生成统计数据请求");
  }).catch(() => {
  });
}

Promise.all([getList(), getAccountList()]);

</script>